package com.pxmeta.skill.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.chat.service.HuanxinService;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.core.redis.RedisCache;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.order.service.IOrderEvaluateService;
import com.pxmeta.order.vo.OrderDetailTagListVO;
import com.pxmeta.party.entity.Association;
import com.pxmeta.party.entity.AssociationUser;
import com.pxmeta.party.entity.Party;
import com.pxmeta.party.entity.SkillPrice;
import com.pxmeta.party.entity.enums.FormTypeEnum;
import com.pxmeta.party.entity.enums.UserLiveStatusEnum;
import com.pxmeta.party.entity.vo.SearchUserVO;
import com.pxmeta.party.entity.vo.SkillVerifyExtraVO;
import com.pxmeta.party.service.*;
import com.pxmeta.skill.entity.Skill;
import com.pxmeta.skill.entity.SkillCertificationForm;
import com.pxmeta.skill.entity.SkillFormItem;
import com.pxmeta.skill.entity.UserSkill;
import com.pxmeta.party.entity.vo.UserSkillVO;
import com.pxmeta.skill.entity.vo.SkillFormItemVO;
import com.pxmeta.skill.entity.vo.SkillPriceVO;
import com.pxmeta.skill.mapper.UserSkillMapper;
import com.pxmeta.order.service.IUserOrderRecordService;
import com.pxmeta.skill.service.ISkillCertificationFormService;
import com.pxmeta.skill.service.ISkillFormItemService;
import com.pxmeta.skill.service.ISkillService;
import com.pxmeta.skill.service.IUserSkillService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.dto.UserDTO;
import com.pxmeta.user.entity.vo.AnchorVO;
import com.pxmeta.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserSkillServiceImpl extends ServiceImpl<UserSkillMapper, UserSkill> implements IUserSkillService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IAssociationService associationService;

    @Autowired
    private ISkillCertificationFormService skillCertificationFormService;

    @Autowired
    private ISkillFormItemService skillFormItemService;

    @Autowired
    private IOrderEvaluateService orderEvaluateService;
    @Autowired
    private  IAssociationUserService associationUserService;

    @Autowired
    private  IPartyService partyService;

    @Autowired
    private  IUserOrderRecordService orderRecordService;

    @Autowired
    private  HuanxinService huanxinService;

    @Autowired
    private ISkillService skillService;

    @Override
    public void submitVerify(Long userId, Integer skillId, String desc) {

        User user = userService.getById(userId);
        String voice = user.getVoice();
        if (StringUtils.isBlank(voice)){
            throw new ServiceException("请先完善声音卡片信息！");
        }

        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId)
                .eq(UserSkill::getSkillId, skillId);

        UserSkill vcu = this.getOne(wrapper);

        if (null != vcu){
            throw new ServiceException("请勿重复提交！");
        }

        UserSkill userSkill = new UserSkill();
        userSkill.setUserId(userId);
        userSkill.setSkillId(skillId);
        userSkill.setDescription(desc);
        userSkill.setStatus(Status.PENDING.getValue());
        this.save(userSkill);
    }

    @Override
    public List<UserSkillVO> getList(String username, Integer skillId, Integer page, Integer size,Integer type) {
        User user = userService.getByUsername(username);

        String province = user.getProvince();

        //随机获取主播
        List<AnchorVO> anchorVOS = Lists.newLinkedList();
        List<Long> anchorUserIds = Lists.newLinkedList();
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();


        if (null != skillId && type == null){
            wrapper.eq(UserSkill::getSkillId, skillId);
        }else if (type !=null){
            wrapper.like(UserSkill::getFeatures,type);
        } else {
            if (page ==1){
                List<AnchorVO> anchorList = partyService.getAnchorList();
                Collections.shuffle(anchorList);
                anchorVOS = anchorList.stream().limit(4).collect(Collectors.toList());
                anchorUserIds = anchorVOS.stream().map(AnchorVO::getId).collect(Collectors.toList());
            }
            wrapper.eq(UserSkill::getIsPrimary, Boolean.TRUE);
        }
        if (CollectionUtil.isNotEmpty(anchorUserIds)){
            wrapper.notIn(UserSkill::getUserId, anchorUserIds);
        }
        wrapper.eq(UserSkill::getIsOpen,Boolean.TRUE);

//        if (StringUtils.isNotBlank(province)){
//            //匹配同省的
//            wrapper.like(UserSkill::getAddress,province);
//        }

        wrapper.orderByDesc(UserSkill::getUserCount,UserSkill::getCreateTime);
        List<UserSkill> list = this.page(new Page<>(page, size),wrapper).getRecords();

        List<Long> userIds = list.stream().map(UserSkill::getUserId).collect(Collectors.toList());
        if (userIds.isEmpty()){
            return Lists.newLinkedList();
        }

        List<User> users = userService.listByIds(userIds);
//        List<String> usernames = users.stream().map(User::getUsername).collect(Collectors.toList());
//
//        JSONArray statusList = huanxinService.batchUserStatus(usernames);
//
        Integer sex = user.getSex();
        List<User> onlineUsers = Lists.newLinkedList();
//
//        //处理用户在线状态
//        for (Object obj : statusList) {
//            String str = JSONObject.toJSONString(obj);
//            JSONObject jsonObject = JSONObject.parseObject(str);
//            Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
//            for (Map.Entry<String, Object> entry : entries) {
//                Optional<User> opt = users.stream().filter(u -> u.getUsername().equals(entry.getKey())).findFirst();
//                if (opt.isPresent() && opt.get().getUsername().equals(entry.getKey()) && "online".equals(entry.getValue())) {
//                    onlineUsers.add(opt.get());
//                    break;
//                }
//            }
//        }

        //在线用户
        List<Long> onlineUserIds = onlineUsers.stream().map(User::getId).collect(Collectors.toList());

        List<UserSkill> onlineList = list.stream().filter(l -> onlineUserIds.contains(l.getUserId())).collect(Collectors.toList());

        List<UserSkill> otherList = list.stream().filter(l -> !onlineUserIds.contains(l.getUserId())).collect(Collectors.toList());
        list.clear();
        list.addAll(onlineList);
        list.addAll(otherList);
        Collections.shuffle(list);

        List<String> maleUsernames = users.stream().filter(u -> u.getSex().equals(1)).map(User::getUsername).collect(Collectors.toList());
        List<String> femaleUsernames = users.stream().filter(u -> u.getSex().equals(2)).map(User::getUsername).collect(Collectors.toList());


//        Boolean accost = redisCache.getCacheObject("accost_"+username);
//        if (accost == null ){
//            redisCache.setCacheObject("accost_"+username,Boolean.TRUE,1, TimeUnit.DAYS);
//
//            List<String> textList = Lists.newLinkedList();
//            if (sex !=null && sex ==1){
//                textList.add("哈喽打游戏吗");
//                textList.add("哥哥打游戏吗");
//                textList.add("你好呀");
//                textList.add("可以做那个撩动你的女孩子嘛");
//                textList.add("你好呀你是哪里的呀");
//                textList.add("哥哥谈个恋爱吗？");
//                textList.add("如果一定要认识的话，用什么方式最好呢？");
//                textList.add("哈喽哥哥");
//                textList.add("你是来交朋友的还是处对象的呀~");
//                textList.add("喜欢多一点是心动，心动多一点是爱，比爱多一点全是你");
//                textList.add("别人都想偷你这个人 我偷个小心心可以吗");
//                textList.add("哈喽哈喽，认识一下嘛");
//                textList.add("你就像山里的游客，边走边爱，四海为家，我希望你可以成为权欲的养猫者 不去看路人 不去换爱人，互动一下 让这里成为你的家，我的意思是，我想认识你");
//                textList.add("贴贴");
//                textList.add("交个朋友嘛？");
//                textList.add("你是哪里的呀？");
//                textList.add("在吗？");
//                textList.add("在干嘛呢？");
//                List<String> accostUsers = getRandomElements(femaleUsernames);
//                for (String accostUserName : accostUsers) {
//                    Collections.shuffle(textList);
//                    huanxinService.sendTextToUser(accostUserName,username,textList.get(0));
//                }
//            }else {
//                textList.add("哈喽小姐姐");
//                textList.add("你会什么技能呀");
//                textList.add("打游戏吗");
//
//                textList.add("在吗？");
//                textList.add("哈喽");
//                textList.add("你好呀");
//                textList.add("你是哪里的呀");
//                textList.add("嘿嘿嘿，我来啦");
//                textList.add("干嘛呢");
//                textList.add("有点无聊哦~ 你在干嘛");
//                textList.add("你好");
//                List<String> accostUsers = getRandomElements(maleUsernames);
//                for (String accostUserName : accostUsers) {
//                    Collections.shuffle(textList);
//                    huanxinService.sendTextToUser(accostUserName,username,textList.get(0));
//                }
//            }
//        }


        //扣费
//        SkillPrice skillPrice = servicePriceService.getDefaultBySkillId(1);
        List<UserSkillVO> finalList = Lists.newLinkedList();
        userIds.addAll(anchorUserIds);
        List<UserDTO> dtoList = userService.getUserInfos(user.getId(),userIds);
        for (UserDTO dto : dtoList) {
            anchorVOS.forEach(a->{
                if (a.getId().equals(dto.getId())){
                    dto.setPartyId(a.getPartyId());
                    dto.setLiveStatus(UserLiveStatusEnum.VOICE_LIVE.getStatus());
                }
            });
        }
        List<UserSkillVO> liveUserList = Lists.newLinkedList();
        for (AnchorVO anchorVO : anchorVOS) {
            UserSkill userSkill = new UserSkill();
            userSkill.setUserId(anchorVO.getId());
            userSkill.setDescription(anchorVO.getPartyTitle());
            list.add(0,userSkill);
        }
        for (UserSkill us : list) {
            UserSkillVO vo = new UserSkillVO();
            try{
                for (UserDTO userDTO : dtoList) {
                    if (userDTO.getId().equals(us.getUserId())){
                        userDTO.setIntro(us.getDescription());
                        vo.setUserInfo(userDTO);
                        break;
                    }
                }

                Long orderCount = orderRecordService.getOrderCount(us.getUserId());
                vo.setOrderCount(orderCount);
                vo.setSkillIcon(us.getSkillIcon());
                vo.setSkillName(us.getSkillName());
                vo.setDesc(us.getDescription());
//                vo.setServicePriceId(skillPrice.getId());
                if (type != null && type == 1){
                    vo.setPrice(100);
                }else {
                    vo.setPrice(us.getPrice());
                }

                vo.setOriginalPrice(us.getOriginalPrice());
                vo.setVoiceUrl(us.getVoiceUrl());
                vo.setPreferential(us.getPreferential());
                vo.setUnit(us.getUnit());
                vo.setGrade(us.getGrade());
                vo.setSkillId(us.getSkillId());
                Double rate = orderEvaluateService.getSatisfiedRate(us.getUserId());
                vo.setScore(rate);
                if (vo.getUserInfo() != null && UserLiveStatusEnum.VOICE_LIVE.getStatus().equals(vo.getUserInfo().getLiveStatus())){
                    liveUserList.add(vo);
                    continue;
                }
                finalList.add(vo);
            }catch (Exception e){
                log.error("获取用户信息失败",e);
            }


        }
        liveUserList.addAll(finalList);
        return liveUserList;
    }

    @Override
    public List<SearchUserVO> searchUsers(String keyword, Integer page, Integer size) {
        return baseMapper.searchUsers(new Page<>(page,size),keyword);
    }


    public static List<String> getRandomElements(List<String> inputList) {
        if (CollectionUtil.isEmpty(inputList)){
            return Lists.newLinkedList();
        }
        Random random = new Random();
        int elementsToSelect = random.nextInt(4) + 2; // Randomly selects 2 to 5 elements

        int listSize = inputList.size();
        if (listSize <= elementsToSelect) {
            return inputList; // Return the whole list if its size is less than or equal to elementsToSelect
        }

        List<String> randomElements = new ArrayList<>();
        for (int i = 0; i < elementsToSelect; i++) {
            int randomIndex = random.nextInt(listSize);
            randomElements.add(inputList.get(randomIndex));
        }

        return randomElements;
    }

    @Override
    public List<UserSkill> getUserList(Long userId) {
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId);
        List<UserSkill> list = this.list(wrapper);
        for (UserSkill userSkill : list) {
            Double rate = orderEvaluateService.getSatisfiedRate(userSkill.getUserId());
            userSkill.setApplauseRate(rate.intValue());
        }
        return list;
    }

    @Override
    public List<UserSkill> getUserSkillList(Long currentUserId, String username) {
        User user = userService.getByUsername(username);
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, user.getId())
                .eq(UserSkill::getIsOpen, Boolean.TRUE);

        List<UserSkill> list = this.list(wrapper);
        for (UserSkill userSkill : list) {
            Double rate = orderEvaluateService.getSatisfiedRate(userSkill.getUserId());
            SkillPriceVO price = getPrice(currentUserId, user.getId(), userSkill.getSkillId(), userSkill.getExtraInfo());
            userSkill.setApplauseRate(rate.intValue());
            userSkill.setOriginalPrice(price.getOriginalPrice());
            userSkill.setPrice(price.getPrice());
        }
        return list;
    }

    @Override
    public void skillVerify(Long userId, Integer skillId, String grade, List<String> imgList, String introduce, String voice, List<SkillVerifyExtraVO> extraList) {
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId)
                .eq(UserSkill::getSkillId, skillId);

        Skill skill = skillService.getById(skillId);
        if (null == skill){
            throw new ServiceException("技能不存在！");
        }

        String skillFeatures = "";
        for (SkillVerifyExtraVO extraVO : extraList) {
            Integer type = extraVO.getFormType();
            if (type!=null &&type == 10){
                List<SkillFormItemVO> items = extraVO.getItems();
                List<Integer> itemIds = items.stream().map(SkillFormItemVO::getId).collect(Collectors.toList());
                if (!CollectionUtil.isEmpty(itemIds)){
                    List<SkillFormItem> list = skillFormItemService.listByIds(itemIds);
                    skillFeatures = list.stream().map(SkillFormItem::getValue).collect(Collectors.joining(","));
                }

            }
        }

        UserSkill vcu = this.getOne(wrapper);

        UserSkill userSkill = new UserSkill();
        userSkill.setUserId(userId);
        userSkill.setSkillId(skillId);
        userSkill.setDescription(introduce);
        userSkill.setGrade(grade);
        userSkill.setFeatures(skillFeatures);
        userSkill.setSkillIcon(skill.getIcon());
        userSkill.setSkillName(skill.getName());
        userSkill.setUnit(skill.getUnit());
        userSkill.setVoiceUrl(voice);

        //判断是否有认证过的技能,如果是第一次认证，则当前认证的技能设置为主要技能。
        wrapper.clear();
        wrapper.eq(UserSkill::getUserId, userId);
        long count = this.count(wrapper);
        if (count==0){
            userSkill.setIsPrimary(Boolean.TRUE);
        }else {
            userSkill.setIsPrimary(Boolean.FALSE);
        }

        for (SkillVerifyExtraVO vo : extraList) {
            //处理价格
            if (FormTypeEnum.PRICE.getType().equals(vo.getFormType())){
                List<SkillFormItemVO> items = vo.getItems();
                SkillFormItemVO itemVO = items.get(0);
                Integer itemId = itemVO.getId();
                SkillFormItem item = skillFormItemService.getById(itemId);
                String value = item.getValue();
                Integer price = Integer.valueOf(value);
                userSkill.setPrice(price);
                break;
            }
        }

        if (CollectionUtil.isNotEmpty(extraList)){
            String extraInfo = JSONObject.toJSONString(extraList);
            userSkill.setExtraInfo(extraInfo);
        }
        if (CollectionUtil.isNotEmpty(imgList)){
            userSkill.setImgUrls(StrUtil.join(",",imgList));
        }

        userSkill.setStatus(Status.PENDING.getValue());

        if (null != vcu){
            userSkill.setId(vcu.getId());
            this.updateById(userSkill);
        }else {
            this.save(userSkill);
        }
    }

    @Override
    public List<UserSkill> getUserSkillList(Long userId) {

        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId);
        return this.list(wrapper);
    }

    @Override
    public void closeUserSkill(Long userId, Integer skillId) {
        UserSkill userSkill = getUserSkill(userId, skillId);
        if (userSkill==null){
            throw new ServiceException("数据不存在！");
        }
        userSkill.setIsOpen(Boolean.FALSE);
        this.updateById(userSkill);
    }

    @Override
    public void openUserSkill(Long userId, Integer skillId) {

        UserSkill userSkill = getUserSkill(userId, skillId);
        if (userSkill==null){
            throw new ServiceException("数据不存在！");
        }
        userSkill.setIsOpen(Boolean.TRUE);
        this.updateById(userSkill);
    }


    @Override
    public UserSkill getUserSkill(Long userId, Integer skillId){
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId)
                .eq(UserSkill::getSkillId, skillId);

        return this.getOne(wrapper);
    }



    /**
     * 判断是否满足每日一币
     * @return
     */
    @Override
    public boolean checkMeetOneCoinFeatures(Long userSkillId, Long buyerId){
        UserSkill userSKill = this.getById(userSkillId);
        String features = userSKill.getFeatures();
        if (StringUtils.isNotBlank(features)){
            List<String> featureList = Arrays.asList(features.split(","));
            //并且用户今天没有下单过首单一币
            if (featureList.contains("1")){
                Boolean firstPayToday = orderRecordService.checkFirstPayOneCoinToday(buyerId);
                if (!firstPayToday){
                    return Boolean.TRUE;
                }
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public List<User> sendAccompanyUsers(String partyId, Integer skillId, Integer sex,String remark,Long dispatchId) {
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getSkillId, skillId)
                .eq(UserSkill::getIsOpen, Boolean.TRUE)
                .last("limit 2500");
        List<UserSkill> list = this.list(wrapper);
        List<Long> userIds = list.stream().map(UserSkill::getUserId).collect(Collectors.toList());
        if (userIds.isEmpty()){
            return Lists.newArrayList();
        }
        List<User> users = userService.listByIds(userIds);

        Skill skill = skillService.getById(skillId);

        String content = "["+skill.getName()+"]:"+remark;
        Party party = partyService.getById(partyId);
        Integer type = 1;
        Long associationId = party.getAssociationId();
        if (associationId != null){
            Association association = associationService.getById(associationId);
             type = association.getType();
        }
        List<String> to = Lists.newLinkedList();
        //如果是工会厅。派单给当下所有工会成员
        if (associationId != null && type != 0){
            List<Long> associationUserIds = associationUserService.getSigningList(associationId, Status.SUCCESS.getValue(), 1, 1000).getRecords().stream().map(AssociationUser::getUserId).collect(Collectors.toList());
            if (!associationUserIds.isEmpty()){
                to = userService.listByIds(associationUserIds).stream().map(User::getUsername).collect(Collectors.toList());
            }
        }else {
            //推送给全平台的陪陪。
            to = this.getUsernamesBySkillId(skillId,sex);
        }


        String customEvent = "party_order";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("party_id",partyId);
        jsonObject.put("dispatchId",dispatchId.toString());
        jsonObject.put("title",party.getTitle());
        jsonObject.put("content",content);
        jsonObject.put("status",Status.PENDING.getValue());
//        for (User user : users) {
//            huanxinService.sendExtMsgToUser(customEvent,remark);
//        }

        if (to.size()>600){
            List<List<String>> partition = Lists.partition(to, 600);
            for (List<String> finalList : partition) {
                huanxinService.sendExtMsgToUser("10006703",finalList,customEvent,jsonObject);
            }
        }else {
            huanxinService.sendExtMsgToUser("10006703",to,customEvent,jsonObject);
        }

        return users;
    }

    private List<String> getUsernamesBySkillId(Integer skillId, Integer sex) {
        List<Long> userIds = baseMapper.getAllUserIds(skillId);
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
//        if (sex !=null && sex != 0){
//            wrapper.eq(User::getSex, sex);
//        }
        wrapper.in(User::getId, userIds)
                .orderByDesc(User::getCreateTime);
        return userService.list(wrapper).stream().map(User::getUsername).collect(Collectors.toList());
    }

    @Override
    public void updateAddress(Long userId, String addressStr) {
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId);

        List<UserSkill> list = this.list(wrapper);
        if (!list.isEmpty()){
            for (UserSkill userSkill : list) {
                userSkill.setAddress(addressStr);
            }
            this.updateBatchById(list);
        }
    }

    @Override
    public Boolean checkIsAccompany(Long userId) {
        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId,userId);
        long count = this.count(wrapper);
        return count>0;
    }

    @Override
    public void verifyUserSkill(Long userId, Long userSkillId) {

        User user = userService.getById(userId);
        String username = user.getUsername();

        UserSkill userSkill = this.getById(userSkillId);
        userSkill.setStatus(Status.SUCCESS.getValue());
        this.updateById(userSkill);
        String skillName = userSkill.getSkillName();
        List<String> to = Lists.newLinkedList();
        to.add(username);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("skill_id",userSkill.getSkillId().toString());
        jsonObject.put("title",skillName + "技能审核通过！");
        jsonObject.put("content","快去完善技能信息，开始接单吧！");
        jsonObject.put("status", Status.SUCCESS.getValue());
        huanxinService.sendExtMsgToUser("10006704",to,"skill_verify",jsonObject);
    }

    /**
     * 用户技能详情
     * @param userId
     * @param skillId
     * @return
     */
    @Override
    public UserSkillVO getUserSkillDetail(Long currentUserId, Long userId, Integer skillId) {

        LambdaQueryWrapper<UserSkill> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserSkill::getUserId, userId)
                .eq(UserSkill::getSkillId, skillId);
        UserSkillVO vo = new UserSkillVO();
        UserSkill userSkill = this.getOne(wrapper);
        String extraInfo = userSkill.getExtraInfo();
        vo.setPrice(userSkill.getPrice());
        vo.setOriginalPrice(userSkill.getOriginalPrice());

        if (StringUtils.isNotBlank(extraInfo)){
            List<SkillVerifyExtraVO> extraList = JSONObject.parseArray(extraInfo, SkillVerifyExtraVO.class);
            SkillPriceVO price = this.getPrice(currentUserId, userId, skillId, extraInfo);
            vo.setOriginalPrice(price.getOriginalPrice());
            vo.setPrice(price.getPrice());
            List<Integer> formIds;
            if (extraList.size()>1){
                formIds = extraList.stream().filter(l->{
                    if(l.getFormType().equals(FormTypeEnum.PRICE.getType())){
                        return Boolean.FALSE;
                    }
                    return Boolean.TRUE;
                }).map(SkillVerifyExtraVO::getFormId).collect(Collectors.toList());
            }else {
                formIds = extraList.stream().map(SkillVerifyExtraVO::getFormId).collect(Collectors.toList());
            }
            List<SkillCertificationForm> formList = Lists.newLinkedList();
            if (!formIds.isEmpty()){
                formList = skillCertificationFormService.listByIds(formIds);
            }
            for (SkillCertificationForm form : formList) {
                Optional<SkillVerifyExtraVO> opt = extraList.stream().filter(e -> e.getFormId().equals(form.getId())).findFirst();
                if (opt.isPresent()){
                    SkillVerifyExtraVO extraVO = opt.get();
                    List<SkillFormItemVO> items = extraVO.getItems();
                    List<String> itemNames = items.stream().map(SkillFormItemVO::getName).collect(Collectors.toList());
                    form.setItems(itemNames);
                }
            }
            vo.setExtras(formList);
        }

        /**
         * 是否满足每日一币
         */
        boolean meetOneCoinFeatures = this.checkMeetOneCoinFeatures(userSkill.getId(), currentUserId);
        if (meetOneCoinFeatures){
            vo.setPrice(100);
        }
        UserDTO dto = userService.getUserInfo(currentUserId, userId);
        Long orderCount = orderRecordService.getOrderCount(userId);
        vo.setOrderCount(orderCount);
        dto.setIntro(userSkill.getDescription());
        vo.setUserInfo(dto);
        //评论数
        Long evaluateCount = orderEvaluateService.getEvaluateCount(userId);
        vo.setEvaluateCount(evaluateCount);
        List<OrderDetailTagListVO> tags = orderEvaluateService.getSkillDetailTags(userSkill.getUserId(), userSkill.getSkillId());
        vo.setTags(tags);
        vo.setUserSkillId(userSkill.getId());
        vo.setSkillIcon(userSkill.getSkillIcon());
        vo.setSkillName(userSkill.getSkillName());
        vo.setDesc(userSkill.getDescription());
        vo.setImgUrls(userSkill.getImgUrls());
        Double rate = orderEvaluateService.getSatisfiedRate(userId);
        vo.setScore(rate);
        vo.setVoiceUrl(userSkill.getVoiceUrl());
        vo.setPreferential(userSkill.getPreferential());
        vo.setUnit(userSkill.getUnit());
        vo.setGrade(userSkill.getGrade());
        return vo;
    }

    @Override
    public SkillPriceVO getPrice(Long currentUserId,Long userSkillId,Integer count) {
        UserSkill userSkill = this.getById(userSkillId);
        SkillPriceVO priceVO = getPrice(currentUserId, userSkill.getUserId(), userSkill.getSkillId(), userSkill.getExtraInfo());
        if (priceVO.getPreferentialType()==2){
            Integer totalPrice = priceVO.getPrice() + priceVO.getOriginalPrice()*(count-1);
            priceVO.setTotalPrice(totalPrice);
        }else {
            Integer price = priceVO.getPrice();
            priceVO.setTotalPrice(price * count);
        }
        return priceVO;
    }


    public SkillPriceVO getPrice(Long currentUserId, Long targetUserId, Integer skillId, String extraInfo){

        UserSkill userSkill = getUserSkill(targetUserId, skillId);
        SkillPriceVO vo = new SkillPriceVO();
        vo.setPrice(userSkill.getPrice());
        vo.setOriginalPrice(userSkill.getOriginalPrice());
        vo.setPreferentialType(0);
        if (StringUtils.isNotBlank(extraInfo)) {
            List<SkillVerifyExtraVO> extraList = JSONObject.parseArray(extraInfo, SkillVerifyExtraVO.class);
            //查询优惠
            Optional<SkillVerifyExtraVO> first = extraList.stream().filter(e -> {
                if (e.getFormType().equals(FormTypeEnum.DISCOUNT_METHOD.getType())) {
                    return Boolean.TRUE;
                }
                return Boolean.FALSE;
            }).findFirst();
            if (first.isPresent()) {
                SkillVerifyExtraVO extraVO = first.get();
                List<SkillFormItemVO> items = extraVO.getItems();
                SkillFormItemVO skillFormItemVO = items.get(0);
                String name = skillFormItemVO.getName();
                Optional<SkillVerifyExtraVO> opt = extraList.stream().filter(e -> {
                    if (e.getFormType().equals(FormTypeEnum.DISCOUNT.getType())) {
                        return Boolean.TRUE;
                    }
                    return Boolean.FALSE;
                }).findFirst();
                if (opt.isPresent()) {
                    SkillFormItemVO discountVo = opt.get().getItems().get(0);
                    Integer itemId = discountVo.getId();
                    //查询折扣数
                    SkillFormItem item = skillFormItemService.getById(itemId);
                    String value = item.getValue();
                    if ("折扣优惠".equals(name)) {
                        vo.setOriginalPrice(userSkill.getPrice());
                        //计算折扣后的价格

                        int finalPrice = BigDecimal.valueOf(userSkill.getPrice() * Double.parseDouble(value)).setScale(0, RoundingMode.HALF_UP).intValue();
                        vo.setPrice(finalPrice);
                        vo.setPreferentialType(1);
                    }
                    if ("首单优惠".equals(name)) {
                        //判断用户是否是第一次下单
                        Boolean firstPay = orderRecordService.checkFirstPay(currentUserId, targetUserId, skillId);
                        //如果是第一次下单
                        if (firstPay) {
                            //计算优惠。
                            vo.setOriginalPrice(userSkill.getPrice());
                            vo.setPrice(Integer.valueOf(value));
                            vo.setPreferentialType(2);
                        }
                    }
                }

            }
        }
        return vo;
    }
}
